Tanstack Routerでfile-based routing
from TanStack Router
file-system based routingできる
https://tanstack.com/router/v1/docs/framework/react/routing/file-based-routing
https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing
https://tanstack.com/router/latest/docs/framework/react/routing/file-naming-conventions
code:_
src/
├── routes/ ← route 定義
│ ├── __root.tsx ← routeのRoot(createRootRoute)
│ │ <Outlet />で子ルートをレンダリング
│ │ 共通の <Link> やナビゲーション
│ │
│ ├── index.tsx ← "/" に対応(createFileRoute("/"))
│ └── about.tsx ← "/about" に対応(createFileRoute("/about"))
│
├── main.tsx ← エントリーポイント
│ routeTree.gen.ts を import
│ createRouter({ routeTree }) でルーター作成
│ <RouterProvider router={router} />
│
├── 📄 routeTree.gen.ts ← tsrで自動生成される
ファイル構造に基づいてルートツリーを構築
src/routes/__root.tsx
https://tanstack.com/router/latest/docs/framework/react/quick-start#srcroutes__roottsx
createRootRouteを使う
他では、 createFileRoute を使ってルートを定義
https://tanstack.com/router/latest/docs/framework/react/quick-start#srcroutesindextsx
code:ts
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => fetchPost(params.postId),
component: PostPage,
errorComponent: ErrorComponent,
pendingComponent: LoadingComponent,
})
file basedだけど'/posts/$postId'は自分で指定するんやmrsekut.icon
自動で型推論されるので params.postId は型安全
エントリポイント
createRouter
ルーターインスタンスの作成
https://tanstack.com/router/latest/docs/framework/react/quick-start#srcmaintsx
bun run devして起動し続けてると
λ bun tsr generateも自動で行われるし、
src/routes/内にtsファイルを作ると、自動でrouteの雛形が作られて体験が良い